import { createStore } from 'vuex'
import menu from './modules/menu'
import login from './modules/login'
import permission from './modules/permission'
import { SET_ACCESS, UPDATE_ACCESS } from './mutation-types'
const accessLoginKey = 'alk'
let accessData:any = {}
if(localStorage[accessLoginKey]) {
    accessData = JSON.parse(window.atob(localStorage[accessLoginKey]))
}

export default createStore({
    modules : {
        menu : menu,
        login,
        permission
    },

    state: {
        refreshLoginInterval : 300,
        accessToken : accessData.accessToken || '',
        accessExpireIn : accessData.accessExpireIn || 0,
        refreshToken : accessData.refreshToken || '',
        roleType : accessData.hasOwnProperty('roleType') ? accessData.roleType : -1,
        king : accessData.hasOwnProperty('king') ? accessData.king : 0,
    },

    mutations : {
        [SET_ACCESS](state, {accessToken, expire, refreshToken, roleType, king}) {
            const accessExpireIn = (new Date()).getTime() / 1000 + expire
            state.accessToken = accessToken
            state.accessExpireIn = accessExpireIn
            state.refreshToken = refreshToken
            localStorage.setItem(accessLoginKey, window.btoa(JSON.stringify({roleType, king, accessToken, accessExpireIn, refreshToken})))
        },

        [UPDATE_ACCESS](state, {accessToken, refreshToken, expire}) {
            console.log('更新', accessToken,refreshToken,expire)
            const accessExpireIn = (new Date()).getTime() / 1000 + expire
            state.accessExpireIn = accessExpireIn
            state.accessToken = accessToken
            state.refreshToken = refreshToken
            accessData.accessToken = accessToken
            accessData.refreshToken = refreshToken
            accessData.accessExpireIn = accessExpireIn
            localStorage.setItem(accessLoginKey, window.btoa(JSON.stringify(accessData)))
        }
    },

    getters : {
        accessExpireStatus(state) {
            return (state.accessExpireIn - ((new Date()).getTime() / 1000)) > 900
        },

        isPlatform : (state) => state.roleType == 0,
        isMerchant : (state) => state.roleType == 1,
        isSubMerchant : (state) => state.roleType == 2,
    }
})